package org.xqh.utils.map;

import com.alibaba.fastjson.JSON;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpResult;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import org.xqh.test.yzs.nlu.NLURequestUtils;
import org.xqh.utils.encrypt.EncryptUtils;
import org.xqh.utils.http.FxHttpClientUtils;
import scala.annotation.meta.param;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.*;

/**
 * @ClassName GaodeMapTest
 * @Description TODO
 * @Author xuqianghui
 * @Date 2022/1/8 11:00
 * @Version 1.0
 */
public class GaodeMapTest {

    public static final String regeo_url = "https://restapi.amap.com/v3/geocode/regeo?key=%s&location=%s&batch=%s";

    public static final String key = "07a568190a02bb8b836600799419360c";

    public static final String secret = "6ddb6cd352d7c5874f096f9b51444862";

    public static void main(String[] args) throws HttpProcessException {
        regeo(EncryptUtils.urlEncode("117.212103,28.283693|117.07015,28.692589"), true);

//        String testUrl = "http://localhost/test?name=asdfg&key1=key1val&age=11&opt=del&ts=13333&batch=false&key2=key2val";
////        System.out.println(calcSign(testUrl));
    }

    public static void regeo(String location, boolean batch) throws HttpProcessException {
        String reqUrl = String.format(regeo_url, key, location, batch);
        String sign = calcSign(reqUrl);
        reqUrl = reqUrl+"&sig="+sign;
        HttpConfig config = FxHttpClientUtils.getHttpConfig(reqUrl);
        HttpResult result = HttpClientUtil.sendAndGetResp(config);
        System.out.println(result.getResult());
    }

    public static String calcSign(String url){

        Map<String, String> map = NLURequestUtils.getParamMap(url);
        String signStr = parseUrlString(map);
        return EncryptUtils.getMd5(signStr.concat(secret));
    }

    /**
     * 使用URL键值对的格式（即key1=value1&key2=value2…）将参数列表拼接成字符串
     */
    public static String parseUrlString(final Map<String, String> requestMap) {
        List<String> keyList = new ArrayList<>(requestMap.keySet());
        Collections.sort(keyList);

        List<String> entryList = new ArrayList<>();
        for (String key : keyList) {
            String value = requestMap.get(key);
            entryList.add(MessageFormat.format("{0}={1}", key, value));
        }
        return String.join("&", entryList);
    }

}
